package design.proxy;

import org.mockito.cglib.proxy.Enhancer;
import org.mockito.cglib.proxy.MethodInterceptor;
import org.mockito.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author wei.yang on 2018/8/8
 */
public class BehaviorInterceptor implements MethodInterceptor {

    private Object object;

    BehaviorInterceptor(Object object) {
        this.object = object;
    }

    /**
     * 创建一个新类
     */
    Object toInstant() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(object.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib design.proxy start:\t" + Thread.currentThread().getName() + "\t" + System.currentTimeMillis());
        Object result = method.invoke(object, objects);
        System.out.println("cglib design.proxy end  :\t" + Thread.currentThread().getName() + "\t" + System.currentTimeMillis());
        return result;
    }
}
